package com.eneat.smartrule.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.eneat.smartrule.mapper.RuleConditionMapper;
import com.eneat.smartrule.model.RuleCondition;
import com.eneat.smartrule.repository.RuleConditionRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class RuleConditionRepoImpl implements RuleConditionRepo {

    @Autowired
    private RuleConditionMapper ruleConditionMapper;
    @Override
    public List<RuleCondition> findByRuleId(Long ruleId) {
        // 1. 一次性查询所有条件（包含子条件）
        List<RuleCondition> allConditions = ruleConditionMapper.selectList(
                new LambdaQueryWrapper<RuleCondition>().eq(RuleCondition::getRuleId, ruleId)
        );

        if (allConditions == null || allConditions.isEmpty()) {
            return new ArrayList<>();
        }


        Map<Long, RuleCondition> conditionMap = new HashMap<>();
        for (RuleCondition condition : allConditions) {
            conditionMap.put(condition.getId(), condition);
        }

        // 3. 构建父子关系
        List<RuleCondition> rootConditions = new ArrayList<>();

        for (RuleCondition condition : allConditions) {
            Long parentId = condition.getParentId();

            if (parentId == null || !conditionMap.containsKey(parentId)) {
                // 没有父节点 或 父节点不存在 → 视为根节点
                rootConditions.add(condition);
            } else {
                // 有父节点 → 添加到父节点的 subRuleConditions 列表中
                RuleCondition parent = conditionMap.get(parentId);
                if (parent.getSubRuleConditions() == null) {
                    parent.setSubRuleConditions(new ArrayList<>());
                }
                parent.getSubRuleConditions().add(condition);
            }
        }

        return rootConditions;
    }

    @Override
    public void save(List<RuleCondition> ruleConditions, Long ruleId, Long parentId) {
        ruleConditions.forEach(ruleCondition -> {
            ruleCondition.setRuleId(ruleId);
            ruleCondition.setParentId(parentId);
            ruleConditionMapper.insert(ruleCondition);
            if (ruleCondition.getSubRuleConditions() != null && !ruleCondition.getSubRuleConditions().isEmpty()) {
                save(ruleCondition.getSubRuleConditions(), ruleId, ruleCondition.getId());
            }
        });

    }
}
